home *** CD-ROM | disk | FTP | other *** search
- Path: info.uah.edu!oreo!gbacon
- From: gbacon@oreo (Greg Bacon)
- Newsgroups: comp.lang.c
- Subject: Re: Examples of using "volatile"?
- Date: 18 Jan 1996 20:03:05 GMT
- Organization: The University of Alabama in Huntsville
- Message-ID: <4dm91p$bsi@info.uah.edu>
- References: <4djoj2$mr1@post.gsfc.nasa.gov>
- Reply-To: gbacon@CS.UAH.Edu
- NNTP-Posting-Host: oreo.aspire.cs.uah.edu
- X-Newsreader: TIN [version 1.2 PL2]
-
- Stephen Maher (Stephen.Maher@gsfc.nasa.gov) wrote:
- : Hi,
-
- : I'd like a concrete example(s) illustrating a reason to
- : use the "volatile" type qualifier.
-
- : I understand the *theory* behind volatile (e.g., to
- : avoid unwanted side-effects?). I also realize it's
- : probably implementation dependent. But some examples
- : from any implementation should help me understand
- : its use a little better.
-
- : Thanks,
-
- : Steve
-
- OK... say for example you have this:
-
- void foo(void)
- {
- int i = 7;
-
- if (i == 7)
- {
- /* do something */
- }
- }
-
- Most optimizers will go ahead and lose the comparison since i _has_
- to be equal to 7, right? Well, not always.. say you have some
- interrupt handler (ahh, the random joy of interrupts) that might
- come in and modify the value of i (highly unlikely, I admit, but this
- is a highly oversimplified example). Well, if the optimizer
- cuts out the test, then it won't matter whether the handler came
- in. The correct version of foo() for this app would look like this:
-
- void foo(void)
- {
- volatile int i = 7;
-
- if (i == 7)
- {
- /* do something */
- }
- }
-
- Basically, like most modifiers, volatile is a hint to the compiler
- that the value of i could change at any time, and not to take its
- value for granted. Of course, the compiler could ignore you since
- it's only a hint, but that wouldn't be a very good compiler :)
-
- Hope this helps,
- Greg
- --
- Greg Bacon <gbacon@cs.uah.edu>
- University of Alabama in Huntsville
- CS Department Systems Support Team
-